import { Notice } from 'view-design'

const websocket_onopen = function () {
  // console.log('open')
}

const websocket_onerror = function () {
  Notice.error({
    title: '错误',
    desc: 'WebSocket连接错误',
    duration: 8
  })
}

const websocket_onclose = function () {
  // console.log('close')
}

const initWebSocket = function (wsPath, layoutItem) {
  if ('WebSocket' in window) {
    try {
      let ws = new WebSocket(wsPath);
      ws.onopen = websocket_onopen;
      ws.onerror = websocket_onerror;
      ws.onclose = websocket_onclose;
      return ws
    } catch (e) {
      let desc = e.message;
      if (layoutItem) {
        desc = 'ID为【'+layoutItem.id+'】的布局块所关联的组件中，WebSocket初始化发生错误，错误信息：' + e.message
      }
      Notice.error({
        title: 'WebSocket初始化错误',
        desc: desc,
        duration: 10
      })
      console.error(e.message)
    }
    return {
      readyState: null
    }
  }else {
    Notice.warning({
      title: '警告',
      desc: '您的浏览器不支持 WebSocket！',
      duration: 10
    })
  }
}

export default {
  initWebSocket
}
